package com.xbongbong.paas.service.impl;

import com.xbongbong.paas.constant.SizeConstant;
import com.xbongbong.paas.pojo.dto.FormDataListDTO;
import com.xbongbong.paas.pojo.vo.ExportFormDataVO;
import com.xbongbong.paas.redis.PaasRedisHelper;
import com.xbongbong.paas.redis.RedisPrefixConstant;
import com.xbongbong.paas.service.ChartExportService;
import com.xbongbong.paas.service.PaasExcelService;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.pro.statistic.enums.StatisticsTypeEnum;
import com.xbongbong.pro.statistic.through.pojo.dto.ResultThroughDTO;
import com.xbongbong.saas.enums.XbbRefTypeEnum;
import com.xbongbong.saas.service.SaasListService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Objects;

/**
 * @author zhouwq
 * @date 2019/6/10 8:57
 */

@Service("chartExportService")
public class ChartExportServiceImpl implements ChartExportService {

    private static final Logger LOG = LoggerFactory.getLogger(ChartExportServiceImpl.class);

    @Resource
    private PaasRedisHelper paasRedisHelper;
    @Resource
    private PaasExcelService paasExcelService;
    @Resource
    private SaasListService saasListService;


    @Override
    public ExportFormDataVO exportChartThroughData(ResultThroughDTO resultThroughDTO){
        ExportFormDataVO exportFormDataVO = new ExportFormDataVO();
        try {
            FormDataListDTO formDataListDTO = new FormDataListDTO();
            if (Objects.equals(resultThroughDTO.getStatisticsType(), StatisticsTypeEnum.CUSTOM_STATISTIC.getCode())) {
                formDataListDTO = saasListService.formDataListAssemble(resultThroughDTO);
                formDataListDTO.setFromExport(1);
                //TODO 临时处理导出固定一万条 等表单导出完成导出1W以上的数据时修改 zhouwq-2019-06-10
                formDataListDTO.setPageSize(SizeConstant.PAGE_SIZE);
                if (Objects.equals(XbbRefTypeEnum.WORK_ORDER.getCode(), formDataListDTO.getBusinessType())) {
                    return paasExcelService.exportWorkOrderData(formDataListDTO);
                }
                return paasExcelService.exportFormData(formDataListDTO);
            }else{
                String hashKey = resultThroughDTO.getCorpid() + "_" + resultThroughDTO.getUserId();
                paasRedisHelper.removeValue(RedisPrefixConstant.EXPORT_STATUS_KEY, hashKey);
                LOG.info("导出失败,接口入口错误");
                return exportFormDataVO;
            }
        }catch (XbbException e){
            String hashKey = resultThroughDTO.getCorpid() + "_" + resultThroughDTO.getUserId();
            paasRedisHelper.removeValue(RedisPrefixConstant.EXPORT_STATUS_KEY, hashKey);
            LOG.error("导出失败", e);
        }
        //导出报表
        return exportFormDataVO;
    }
}
